/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import connection.IMessageListenner;
import database.DataEngine;
import database.SmsInfo;
import database.UserInfo;
import java.util.List;
import log.LogDef;
import log.LogWriter;
import utils.Debug;

/**
 *
 * @author daz
 */
public class ChargeThread implements Runnable, IMessageListenner {

    private int threadDelay = 5000;
    private boolean isRunning;
    private Request request;
    private String host;
    private String port;
    private boolean isConnected;
    private long startTime;
    private DataEngine dataEngine = DataEngine.getInstance();
    private String csPath;
    private LogWriter objWriter;
    private String _csModuleName = "charge";
    private byte _nLogLevel = LogDef.LOG_LEVEL.LOG_INFO;

    public ChargeThread(String host, String port) {
        this.host = host;
        this.port = port;
        initConnection();
    }

    private void initConnection() {
        request = new Request();
        request.initializeConnection(host, port);
        request.setMessageListenner(this);
        isConnected = request.isConnect();
        Debug.d("is connect :" + isConnected);
        if (isConnected) {
        }

    }

    public void start() {
        isRunning = true;
        Thread mainThread = new Thread(this);
        mainThread.start();
    }

    private void printMemory() {
//        System.out.println("Max memory    :" + (Runtime.getRuntime().maxMemory() >> 20));
        System.out.println("--------------------------------------------------------------");
        System.out.println("Free memory   :" + (Runtime.getRuntime().freeMemory() >> 20));
//        System.out.println("Total memmory :" + (Runtime.getRuntime().totalMemory() >> 20));
        System.out.println("Use memmory :" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20));
        Debug.d("isconnect " + request.isConnect());
        Runtime.getRuntime().gc();

    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                Thread.sleep(threadDelay);
            } catch (Exception ex) {
            }
            if (System.currentTimeMillis() - startTime > threadDelay) {
                startTime = System.currentTimeMillis();
                printMemory();
            }
            if (!request.isConnect()) {
                logUserStatus("lost connection", _nLogLevel);
                initConnection();

            } else {
                List<SmsInfo> list = dataEngine.getSmsQueue(0);
                dataEngine.logTransaction(0);
                if (!list.isEmpty()) {
                    while (!list.isEmpty()) {
                        SmsInfo info = list.get(0);
                        Debug.d("nap tien :" + info.getAccName());
                        if (info.getAccName().trim().equals("null")) {
                            String userCharge = dataEngine.getUserCharger(info.getSenderNumber());
                            Debug.d("user charge :" + userCharge);
                            info.setAccName(userCharge);
                        }
                        Debug.d("dau so :" + info.getServiceCode());
                        Debug.d("phone :" + info.getSenderNumber());
                        logUserStatus(info.getAccName() + "," + info.getServiceCode(), _nLogLevel);
                        if (info.isIsGetPass()) {
                            UserInfo userInfo = dataEngine.getUserInfo(info.getAccName());
                            String message = "";
                            if (userInfo == null) {
                                message = "Tai khoan " + info.getAccName() + " khong ton tai. Xin cam on";
                            } else {
                                if (userInfo.getPhoneNumber().equals(info.getSenderNumber())) {
                                    String pass = utils.Utils.getPass();
                                    dataEngine.changePass(info.getAccName(), pass);
                                    message = "Mat khau moi cho nick " + info.getAccName() + " la :" + pass;
                                } else {
                                    message = "Day khong phai la so dien thoai dang ky nick " + info.getAccName() + ". Xin cam on";
                                }
                            }
                            dataEngine.insertMtQueue(info.getServiceNumber(), info.getSenderNumber(), info.getOperator(),
                                    info.getCommandCode(), info.getRequestId(), message);
                        } else {
                            request.chargeSms(info.getServiceCode(), info.getAccName());
                            dataEngine.insertMtQueue(info.getServiceNumber(), info.getSenderNumber(), info.getOperator(),
                                    info.getCommandCode(), info.getRequestId(), getMtMessage(info));
                        }
                        list.remove(0);
                    }
                }

                list = dataEngine.getSmsQueue(1);
//                Debug.d("list size cp :" + list.size());
                dataEngine.logTransaction(1);
                if (!list.isEmpty()) {
                    while (!list.isEmpty()) {
                        SmsInfo info = list.get(0);
                        Debug.d("nap tien :" + info.getAccName());
                        if (info.getAccName().trim().equals("null")) {
                            String userCharge = dataEngine.getUserCharger(info.getSenderNumber());
                            Debug.d("user charge :" + userCharge);
                            info.setAccName(userCharge);
                        }
                        Debug.d("dau so :" + info.getServiceCode());
                        Debug.d("phone :" + info.getSenderNumber());
                        logUserStatus(info.getAccName() + "," + info.getServiceCode(), _nLogLevel);
                        if (info.isIsGetPass()) {
                            UserInfo userInfo = dataEngine.getUserInfo(info.getAccName());
                            String message = "";
                            if (userInfo == null) {
                                message = "Tai khoan " + info.getAccName() + " khong ton tai. Xin cam on";
                            } else {
                                if (userInfo.getPhoneNumber().equals(info.getSenderNumber())) {
                                    String pass = utils.Utils.getPass();
                                    dataEngine.changePass(info.getAccName(), pass);
                                    message = "Mat khau moi cho nick " + info.getAccName() + " la :" + pass;
                                } else {
                                    message = "Day khong phai la so dien thoai dang ky nick " + info.getAccName() + ". Xin cam on";
                                }
                            }
                            dataEngine.insertCpMtQueue(info.getServiceNumber(), info.getSenderNumber(), info.getOperator(),
                                    info.getCommandCode(), info.getRequestId(), info.getCpName(), message);
                        } else {
                            request.chargeSms(info.getServiceCode(), info.getAccName());
                            dataEngine.insertCpMtQueue(info.getServiceNumber(), info.getSenderNumber(), info.getOperator(),
                                    info.getCommandCode(), info.getRequestId(), info.getCpName(), getMtMessage(info));
                        }
                        list.remove(0);
                    }
                }
            }
        }
    }

    private String getMtMessage(SmsInfo smsInfo) {
        String number = smsInfo.getServiceNumber();
        String message = "";
        if (number.charAt(1) == '0') {
            message = "Ban vua kich hoat tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '1') {
            message = "Ban vua nap 10.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '2') {
            message = "Ban vua nap 20.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '3') {
            message = "Ban vua nap 30.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '4') {
            message = "Ban vua nap 40.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '5') {
            message = "Ban vua nap 50.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '6') {
            message = "Ban vua nap 100.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        } else if (number.charAt(1) == '7') {
            message = "Ban vua nap 150.000 xu vao tai khoan FunGame. Tong dai cham soc khach hang la 1900561588. Xin cam on.";
        }
        return message;
    }

    @Override
    public void processMessage(String[] part) {
        if (part[0].equals("PING")) {
            request.ping();
        }
    }

    void setLogFilePath(String logFilePath) {
        this.csPath = logFilePath;
        initLogger();
    }

    private void initLogger() {
        //Init logger
        objWriter = new LogWriter(_csModuleName, _nLogLevel);

        objWriter.setFileLogInfo(true, csPath, _csModuleName,
                LogDef.FILE.CHANGE_ON_SZIE, //Change file when maximum size reached
                LogDef.FILE.MAX_FILE_SIZE / 10, //1M
                LogDef.FILE.MAX_FILE_BACKUP_INDEX,// 1000 file per day
                false //flush immediately
                );
        objWriter.setSysLogInfo(true, "localhost", 513);
        objWriter.setConsoleInfo(true);

        objWriter.open();
    }

    public synchronized void logUserStatus(String logMsg, byte nLevel) {
        if (objWriter != null) {
            objWriter.writeLog(logMsg, nLevel);
        } else {
//            System.out.println("logger null");
        }
    }

    @Override
    public void stop() {
    }
}
